from soj.settings.compare.common import MAX_COMPARE_TIME
from soj.builtin.compare.common import ensure_file,ResultCode,CompareResult,translate_msg
from pathlib import Path
import subprocess as sp
import platform

if platform.system()=="Windows":
    SYSCMD="fc"
else:
    SYSCMD="diff"

class SyscmdCompare:
    def __init__(self,file_p:Path,file_j:Path):
        ensure_file(file_p)
        ensure_file(file_j)
        self.file_p=file_p.resolve().absolute()
        self.file_j=file_j.resolve().absolute()
    def compare(self)->CompareResult:
        try:
            result=sp.run([
                SYSCMD,
                self.file_p,
                self.file_j
            ],timeout=MAX_COMPARE_TIME,capture_output=True,text=True,shell=True)
        except TimeoutError as e:
            return {
                'result_code':ResultCode.FAILED,
                'msg':'[SE:SyscmdCompare] Comparator timed out'
            }
        except Exception as e:
            return {
                'result_code':ResultCode.FAILED,
                'msg':'[SE:SyscmdCompare] Unknown exception raised'
            }
        return {
            'result_code':(ResultCode.ACCEPTABLE if result.returncode==0 
                           else (ResultCode.UNACCEPTABLE if result.returncode==1 else ResultCode.FAILED)),
            'msg':translate_msg(result.stdout)
        }